<template>
  <div class="page-basic">
    <a-form
      :model="formState"
      :rules="basicRules"
      ref="basicRef"
      :labelCol="{ style: { width: '84px' } }"
      :colon="false"
      labelAlign="right"
    >
      <div class="page-basic-hasBtn">
        <a-form-item label="影片名称" name="video_name">
          <a-input
            v-model:value.trim="formState.video_name"
            :maxlength="50"
            placeholder="请输入影片名称"
            class="input-w-304"
          />
          <a-button type="primary" class="ml-[8px]" @click="handleListByName" :loading="nameLoading">获取资料</a-button>
        </a-form-item>
        <a-form-item label="豆瓣ID" class="ml-[33px]" name="beanId">
          <a-input v-model:value.trim="formState.beanId" placeholder="请输入豆瓣ID" class="input-w-304" />
          <a-button type="primary" class="ml-[8px]" @click="handleDetailByBeanId" :loading="beanLoading"
            >获取资料</a-button
          >
        </a-form-item>
      </div>
      <div class="page-basic-classify">
        <a-form-item label="影片分类" class="mr-[47px]" name="video_categ_id">
          <a-cascader
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
            v-model:value="classList"
            change-on-select
            class="m-r-24 w-[200px]"
            :field-names="{ label: 'name', value: 'id', children: 'subcateg' }"
            :options="videoClassList"
            placeholder="全部分类"
            @change="handleSelectChange"
          >
            <template #suffixIcon>
              <a-tooltip placement="top" color="#fff">
                <template #title> 双击选中父级 </template>
                <div class="ellipsis-text">
                  <question-circle-outlined />
                </div>
              </a-tooltip>
            </template>
          </a-cascader>
        </a-form-item>
        <a-form-item class="mr-[47px]" name="video_album_ids">
          <a-select
            v-model:value="formState.video_album_ids"
            mode="multiple"
            max-tag-count="responsive"
            placeholder="影片专辑"
            class="select-w-200"
            :filter-option="filterOption"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option v-for="item in videoAlbumList" :key="item.album_id" :value="item.album_id">{{
              item.album_name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="mr-[47px]" name="video_area_id">
          <a-select
            v-model:value="formState.video_area_id"
            placeholder="地区"
            allowClear
            class="select-w-200"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="undefined" v-if="areaList.length > 0">地区</a-select-option>
            <a-select-option :value="item.area_id" v-for="item in areaList" :key="item.area_id">{{
              item.area_name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="mr-[47px]" name="video_year">
          <a-select
            v-model:value="formState.video_year"
            placeholder="年代"
            allowClear
            class="select-w-200"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="undefined" v-if="yearList.length > 0">年代</a-select-option>
            <a-select-option :value="item" v-for="item in yearList" :key="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="mr-[47px]" name="video_lang">
          <a-select
            v-model:value="formState.video_lang"
            placeholder="语言"
            allowClear
            class="select-w-200"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="undefined" v-if="langList.length > 0">语言</a-select-option>
            <a-select-option :value="item" v-for="item in langList" :key="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="mr-[47px]" name="publish_state">
          <a-select
            v-model:value="formState.publish_state"
            placeholder="完结状态"
            allowClear
            class="select-w-200"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="undefined">完结状态</a-select-option>
            <a-select-option :value="1">已完结</a-select-option>
            <a-select-option :value="2">连载中</a-select-option>
          </a-select>
        </a-form-item>
      </div>
      <div class="page-basic-filmType" v-if="showFilmType && typeList.length > 0">
        <a-form-item label="影片类型" name="type_ids">
          <a-checkbox-group v-model:value="formState.type_ids" name="checkboxgroup" :options="typeList" />
        </a-form-item>
      </div>
      <div class="page-basic-three-column">
        <a-form-item label="演员信息" class="mr-[33px]" name="actor">
          <ScrollSelect
            v-model:newValue="formState.actor_copy"
            placeholder="演员信息"
            :apiUrl="maker_list"
            @get-list="getList"
            @handle-change="handleChange"
          />
        </a-form-item>
        <a-form-item label="影片导演" class="mr-[33px]" name="director">
          <ScrollSelect
            v-model:newValue="formState.director_copy"
            placeholder="演员信息"
            :apiUrl="maker_list"
            @get-list="getList2"
            @handle-change="handleChange2"
          />
        </a-form-item>
        <a-form-item label="上映时间" class="mr-[33px]" name="video_release_date">
          <a-input
            v-model:value="formState.video_release_date"
            :maxlength="100"
            placeholder="请输入上映日期"
            class="w-[400px]"
          />
        </a-form-item>
        <a-form-item label="连载集数" class="mr-[33px]" name="video_episode">
          <a-input
            v-model:value="formState.video_episode"
            :maxlength="50"
            placeholder="请输入连载集数"
            class="w-[400px]"
          />
        </a-form-item>
        <a-form-item label="总集数" class="mr-[33px]" name="video_episode_total">
          <a-input
            v-model:value="formState.video_episode_total"
            :maxlength="50"
            placeholder="请输入总集数"
            class="w-[400px]"
          />
        </a-form-item>
        <a-form-item label="影片时长" class="mr-[33px]" name="video_duration">
          <a-input
            v-model:value="formState.video_duration"
            :maxlength="50"
            placeholder="请输入影片时长"
            class="w-[400px]"
          />
        </a-form-item>
        <a-form-item label="豆瓣评分" class="mr-[33px]" name="video_score_douban">
          <a-input-number
            v-model:value="formState.video_score_douban"
            placeholder="请输入评分"
            class="w-[400px]"
            :min="0"
            :max="10"
            :step="0.1"
          />
        </a-form-item>
        <a-form-item label="IMDB评分" class="mr-[33px]" name="video_score_imdb">
          <a-input-number
            v-model:value="formState.video_score_imdb"
            placeholder="请输入评分"
            class="w-[400px]"
            :min="0"
            :max="10"
            :step="0.1"
          />
        </a-form-item>
        <a-form-item label="影片备注" class="mr-[33px]" name="video_note">
          <a-input
            v-model:value="formState.video_note"
            :maxlength="50"
            placeholder="请输入影片备注"
            class="w-[400px]"
          />
        </a-form-item>
        <a-form-item label="影片看点" class="mr-[33px]" name="video_highlight">
          <a-input
            v-model:value="formState.video_highlight"
            :maxlength="50"
            placeholder="请输入影片看点"
            class="w-[400px]"
          />
        </a-form-item>
        <a-form-item label="是否付费" class="mr-[33px]" name="video_price_type">
          <a-radio-group v-model:value="formState.video_price_type" @change="handlePriceChange">
            <a-radio :value="1" class="m-r-106">免费</a-radio>
            <a-radio :value="2" class="m-r-106" disabled>付费</a-radio>
            <a-radio :value="3" disabled>点播</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="金币" name="video_price" v-if="formState.video_price_type !== 1">
          <a-input
            v-model:value.trim="formState.video_price"
            :maxlength="5"
            class="w-[400px]"
            :placeholder="formState.video_price_type === 2 ? '请填写付费金币数量' : '请填写点播金币数量'"
            suffix="金币"
          />
        </a-form-item>
      </div>
      <div class="page-basic-common">
        <div class="page-basic-common-title">影片简介</div>
        <a-form-item label="简介内容" name="video_introduction">
          <a-textarea
            v-model:value="formState.video_introduction"
            placeholder="请输入影片简介"
            show-count
            :maxlength="1000"
            class="h-[114px] w-[100%]"
          />
        </a-form-item>
      </div>
      <div class="page-basic-common">
        <div class="page-basic-common-title">影片封面</div>
        <div class="page-basic-common-cover">
          <a-form-item label="竖版封面">
            <div>
              <a-radio-group v-model:value="formState.video_cover_vertical_type" @change="handleVerticalChange">
                <a-radio :value="1" class="m-r-120">文件</a-radio>
                <a-radio :value="2">URL</a-radio>
              </a-radio-group>
              <div>
                <div style="display: flex; align-items: center; height: 32px">
                  <UploadImage
                    v-if="formState.video_cover_vertical_type === 1"
                    fileType="0"
                    imgType="1"
                    fileUrl="v1/common/upload"
                    @getImageInfo="getLineImageInfo"
                  >
                    <a-input-search
                      v-model:value="formState.video_cover_vertical"
                      enter-button="上传文件"
                      @search="onLineSearch"
                      readOnly
                      class="w-480"
                    />
                  </UploadImage>
                  <a-input
                    v-else
                    @blur="handleVerticalBlur"
                    v-model:value="formState.video_cover_vertical"
                    placeholder="请输入URL地址"
                    class="w-480"
                  />
                  <a-tooltip placement="right" class="ml-[16px]" color="#fff" v-if="verticalPreviewImage">
                    <template #title>
                      <img alt="example" class="max-w-[300px] max-h-[300px]" :src="verticalPreviewImage" />
                    </template>
                    <a href="javascript:;" class="whitespace-nowrap">
                      <fund-view-outlined class="icon-preview text-[18px]" /> 预览
                    </a>
                  </a-tooltip>
                </div>
                <p class="source-introduce">
                  {{ storage.get('img_type') ? '支持' + storage.get('img_type') + '素材，' : '' }}
                  {{ storage.get('img_size') ? storage.get('img_size') + '以内；' : '' }}建议尺寸331*441px
                </p>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="横版封面">
            <div>
              <a-radio-group v-model:value="formState.video_cover_horizontal_type" @change="handleHorizontalChange">
                <a-radio :value="1" class="m-r-120">文件</a-radio>
                <a-radio :value="2">URL</a-radio>
              </a-radio-group>
              <div>
                <div style="display: flex; align-items: center; height: 32px">
                  <UploadImage
                    v-if="formState.video_cover_horizontal_type === 1"
                    fileType="0"
                    imgType="1"
                    fileUrl="v1/common/upload"
                    @getImageInfo="getRowImageInfo"
                  >
                    <a-input-search
                      v-model:value="formState.video_cover_horizontal"
                      enter-button="上传文件"
                      @search="onRowSearch"
                      readOnly
                      class="w-480"
                    />
                  </UploadImage>
                  <a-input
                    v-else
                    @blur="handleHorizontalBlur"
                    v-model:value="formState.video_cover_horizontal"
                    placeholder="请输入URL地址"
                    class="w-480"
                  />
                  <a-tooltip placement="right" class="ml-[16px]" color="#fff" v-if="horizontalPreviewImage">
                    <template #title>
                      <img
                        alt="example"
                        class="max-w-[300px] max-h-[300px] w-[-webkit-fill-available] object-contain"
                        :src="horizontalPreviewImage"
                      />
                    </template>
                    <a href="javascript:;" class="whitespace-nowrap">
                      <fund-view-outlined class="icon-preview text-[18px]" /> 预览
                    </a>
                  </a-tooltip>
                </div>
                <p class="source-introduce">
                  {{ storage.get('img_type') ? '支持' + storage.get('img_type') + '素材，' : '' }}
                  {{ storage.get('img_size') ? storage.get('img_size') + '以内；' : '' }}建议尺寸327*184px
                </p>
              </div>
            </div>
          </a-form-item>
        </div>
      </div>
      <div class="page-basic-common">
        <div class="page-basic-common-title">播放资源</div>
        <div class="address-content">
          <div class="address-content-playAddress" v-for="(item, index) in formState.video_play_url" :key="item.number">
            <div class="address-content-playAddress-top">
              <div class="left-title whitespace-nowrap">
                <span class="left-title-title">播放地址{{ item.number }}</span>
                <a-tooltip placement="bottom" color="#fff" :overlayStyle="{ minWidth: '300px' }">
                  <template #title>
                    <span style="color: #5e5e5e" v-if="siteType === 1">
                      1、一行一集播放地址；<br />
                      2、集数名称为集选展示标题，例如：第1集、第08期、第2022-08-15期;<br />
                      3、播放地址主要为采集种源系统的资源地址，包含域名或磁力链接，可直接播放；
                    </span>
                    <span style="color: #5e5e5e" v-else>
                      1、一行一集播放地址；<br />
                      2、集数名称为集选展示标题，例如：第1集、第08期、第2022-08-15期;<br />
                      3、外部资源地址，包含域名，可直接播放；
                    </span>
                  </template>
                  <i class="iconfont icon-tishi text-[12px] text-[#595959] mr-0"></i>
                </a-tooltip>
                <a-input
                  v-model:value="item.name"
                  :maxlength="50"
                  :placeholder="siteType === 1 ? '种源资源线路备注名（非必填）' : '外部线路备注名（非必填）'"
                  class="w-[200px] ml-[14px]"
                />
              </div>
              <div class="right-btn">
                <a-button type="primary" size="small" @click="addNewEpisode(index)">新增一集</a-button>
                <a-button type="primary" size="small" @click="clearAddress(index)">清空</a-button>
                <a-button type="primary" size="small" @click="reverseAddress(item, index)">反序</a-button>
                <a-button type="primary" size="small" @click="adjustAddress(item)">校正地址</a-button>
                <a-button danger size="small" @click="deleteAddress(index)">删除</a-button>
              </div>
            </div>
            <div class="address-content-playAddress-addressText">
              <a-table
                id="basicSortTable"
                :ref="(el:any) => setItemRef(el)"
                row-key="id"
                :columns="siteType === 1 ? columns : outColumns"
                :data-source="item.urls"
                :pagination="false"
                :scroll="{ x: 300, y: 171 }"
                :minWidth="450"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.key === 'sort'">
                    <menu-outlined />
                  </template>
                  <template v-else-if="column.key === 'name'">
                    <a-input
                      v-model:value.trim="record.name"
                      :maxlength="30"
                      class="w-[130px]"
                      placeholder="请输入集数名称"
                    />
                  </template>
                  <template v-else-if="column.key === 'url'">
                    <a-input
                      v-model:value.trim="record.url"
                      :placeholder="siteType === 2 ? '请输入播放地址' : '请输入播放地址或磁力链接'"
                    />
                  </template>
                  <template v-else-if="column.key === 'action'">
                    <div class="text-center">
                      <i
                        class="iconfont icon-delete text-[20px] text-[#fe4c4d] cursor-pointer"
                        @click="deleteItem(item.urls, index)"
                      />
                    </div>
                  </template>
                </template>
              </a-table>
            </div>
          </div>
        </div>
        <span style="margin-left: 72px" @click="addAddress">
          <a href="javascript:;" class="whitespace-nowrap">
            <i class="iconfont icon-add text-[16px] mr-[8px]"></i>添加一组播放地址
          </a>
        </span>
        <a-form-item label="影片状态" class="m-t-34" name="video_status">
          <a-radio-group v-model:value="formState.video_status">
            <a-radio :value="1" class="m-r-120">启用</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </div>
    </a-form>
    <modal-view
      title="提示"
      v-model:visible="filmVisible"
      okText="确定"
      cancelText="取消"
      :afterClose="afterCloseEdit"
      @confirm="chooseConfirm"
      @cancel="chooseCancel"
      :width="458"
    >
      <div class="mb-[8px] text-[#262626]">共查询到{{ videoList.length }}部影片，请选择：</div>
      <a-form ref="chooseFilmRef" :model="filmState">
        <a-form-item name="bean_id" :rules="[{ required: true, message: '请选择影片' }]">
          <a-select
            v-model:value="filmState.bean_id"
            placeholder="请选择影片"
            class="w-[380px]"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="item.douban_id" v-for="item in videoList" :key="item.douban_id">
              <div class="flex items-center">
                <a-tooltip placement="left" color="#fff">
                  <template #title>
                    <img :src="item.cover" class="max-w-[200px] max-h-[200px] object-contain" />
                  </template>
                  <img :src="item.cover" class="w-[28px] h-[28px] object-contain" />
                </a-tooltip>
                <span class="ml-[8px]">{{ item.video_name }}</span>
              </div>
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch, inject, nextTick } from 'vue'
import UploadImage from '@/components/components/upload-image/UploadImage.vue'
import { columns, outColumns } from './dataSource'
import Sortable from 'sortablejs'

import { formState, resetExtendFunc, isPopularity } from './state'
import type { AlbumListData } from '@/types/site/albumList'
import ModalView from '@/components/components/modal/ModalView.vue'
import ScrollSelect from './ScrollSelect.vue'
import type { AreaData } from '@/types/site/area'
import { message } from 'ant-design-vue'
import apis from '@/apis'
import { useRouter, useRoute } from 'vue-router'
import { storage } from '@/utils/storage'
import { onUnmounted } from 'vue'
const router = useRouter()
const route = useRoute()
const {
  site: {
    classify_list,
    video_album_list,
    maker_list,
    add_film,
    update_film,
    detail_film,
    detail_film_byBeanId,
    detail_film_byFilmName,
    get_video_option,
    area_list,
    video_type_byClass
  }
} = apis
//必须要写
const VNodes = (_: any, { attrs }: any) => {
  return attrs.vnodes
}

const basicRef = ref()
const chooseFilmRef = ref()
const beanLoading = ref(false)
const nameLoading = ref(false)
const videoId = ref('') //影片id
const videoClassList = ref([])
const videoAlbumList = ref<AlbumListData[]>()
const videoPersonList = ref<{ person_id: string; person_name: string }[]>([])
const directorList = ref<{ person_id: string; person_name: string }[]>([])
const typeList = ref<{ value: string; label: string }[]>([]) //图集类型数据
// const dateFormat = 'YYYY-MM-DD'
// const showTime = ref<Dayjs>() //日期存放变量
// const defaultValue = ref<Dayjs>()
const classList = ref<string[]>([]) //分类数据
const areaList = ref<AreaData[]>([]) //地区数据
const yearList = ref<string[]>([]) //年份数据
const langList = ref<string[]>([]) //获取语言
const siteId = storage.get('siteId') //站点id
const siteType = storage.get('siteType') //站点类型
const baseUrl: any = inject('baseUrl')
const reg = /^(0|\+?[1-9][0-9]{0,4})$/ //五位正整数包含0
const validatePrice = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (formState.video_price_type == 2) {
      return Promise.reject('请填写付费金币数量')
    } else {
      return Promise.reject('请填写点播金币数量')
    }
  } else if (!reg.test(value)) {
    return Promise.reject('请输入0-99999的金币数量')
  } else {
    return Promise.resolve()
  }
}
const basicRules = reactive({
  video_name: [{ required: true, message: '请输入影片名称' }],
  video_price: [{ required: true, validator: validatePrice, trigger: 'blur' }]
})
const filmVisible = ref(false)
const filmState = reactive<{ bean_id: string | undefined }>({ bean_id: undefined })
const videoList = ref<{ douban_id: string; video_name: string; cover: string }[]>([])
//重置表单
const afterCloseEdit = () => {
  chooseFilmRef.value.resetFields()
}
const chooseConfirm = () => {
  chooseFilmRef.value.validate().then(() => {
    console.log(formState.beanId, 'formState.beanId')
    formState.beanId = filmState.bean_id
    handleDetailByBeanId()
    filmVisible.value = false
  })
}
const chooseCancel = () => {
  filmVisible.value = false
}
const showFilmType = computed(() => {
  if (formState.video_categ_id && formState.video_categ_id != '0') return true
  return false
})

const verticalPreviewImage: any = ref() //图片预览地址
const horizontalPreviewImage: any = ref() //图片预览地址
const filterOption = (input: string, option: any) => {
  console.log('input: string, option: any: ', input, option)
  // return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
//日期
// const handleTimeChange = (date: string, dateString: string) => {
//   console.log('date: ', date, dateString)
// console.log('showTime.value: ', showTime.value)
// }

//横版
const onRowSearch = (searchValue: string) => {
  console.log('use value', searchValue)
}
//竖版封面切换事件
const handleVerticalChange = (e: any) => {
  basicRef.value.clearValidate(['video_cover_vertical'])
  console.log('e: ', e)
  formState.video_cover_vertical = ''
  verticalPreviewImage.value = ''
}
//横版封面切换事件
const handleHorizontalChange = (e: any) => {
  console.log('e: ', e)
  basicRef.value.clearValidate(['video_cover_horizontal'])
  formState.video_cover_horizontal = ''
  horizontalPreviewImage.value = ''
}
const getRowImageInfo = (value: any) => {
  console.log('value: ', value)
  formState.video_cover_horizontal = value
  if (formState.video_cover_horizontal_type === 1) return (horizontalPreviewImage.value = baseUrl + value)
  horizontalPreviewImage.value = value
}
const handleHorizontalBlur = (e: any) => {
  horizontalPreviewImage.value = e.target.value
}
const handleVerticalBlur = (e: any) => {
  verticalPreviewImage.value = e.target.value
}
//竖版
const onLineSearch = (searchValue: string) => {
  console.log('use value', searchValue)
}

const getLineImageInfo = (value: any) => {
  console.log('value: ', value)
  formState.video_cover_vertical = value
  if (formState.video_cover_vertical_type === 1) return (verticalPreviewImage.value = baseUrl + value)
  verticalPreviewImage.value = value
}
//获取影片参数
const getVideoOption = () => {
  get_video_option({ site_id: siteId }).then((res: any) => {
    console.log('获取语言: ', res.lang)
    if (res.lang.trim().length > 0) {
      langList.value = res.lang.split(',')
    } else {
      langList.value = []
    }
    if (res.year.trim().length > 0) {
      yearList.value = res.year.split(',')
    } else {
      yearList.value = []
    }
  })
}
//根据分类查类型
const getTypeByClass = () => {
  console.log('formState.picture_categ_id: ', formState.video_categ_id)
  if (!formState.video_categ_id || formState.video_categ_id === '0') return false
  video_type_byClass({ categ_id: formState.video_categ_id }).then((res: any) => {
    typeList.value = res?.types ?? []
    if (typeList.value.length <= 0) return false
    typeList.value = typeList.value.map((item: any) => {
      return { value: item.type_id, label: item.type_name }
    })
  })
}
//获取地区
const getArea = () => {
  area_list({ site_id: siteId }).then((res: any) => {
    console.log('获取地区: ', res.areas)
    areaList.value = res?.areas ?? []
  })
}
//树形数据数据处理 过滤所有子节点 递归
const parseTreeArray = (treeArray: any, disable: boolean) => {
  treeArray.forEach((item: any) => {
    if (item.subcateg && item.subcateg.length > 0) {
      if (item.status === 2) {
        item.disabled = true
        parseTreeArray(item.subcateg, true)
      }
    } else {
      for (var key in item) {
        if (Array.isArray(item[key]) && item[key].length === 0) {
          delete item[key]
        }
      }
      if (disable) {
        item.disabled = true
      } else {
        if (item.status === 2) {
          item.disabled = true
        }
      }
    }
  })
}
//获取分类接口
const getVideoList = () => {
  classify_list({ site_id: siteId, categ_status: 1 }).then((res: any) => {
    if (res?.categ.length === 0) return []
    parseTreeArray(res?.categ, false)
    console.log('res?.categ: ', res?.categ)
    // res?.categ.unshift({ id: undefined, name: '全部分类' })
    videoClassList.value = res?.categ
  })
}
//获取分类接口
const getAlbumList = () => {
  video_album_list({ site_id: siteId, album_status: 1 }).then((res: any) => {
    if (res?.albums.length === 0) return []
    videoAlbumList.value = res?.albums ?? []
  })
}

const getList = (list: any) => {
  dropDownData.value.options.concat(list)
}
const getList2 = (list: any) => {
  dropDownData.value.options2.concat(list)
}
const handleChange = (option: any) => {
  formState.actor = [...option]
}
const handleChange2 = (option: any) => {
  formState.director = [...option]
}
interface IPerson {
  person_id: string
  person_name: string
}

const dropDownData = ref<{ options: IPerson[]; options2: IPerson[] }>({
  options: [], //演员下拉项列表
  options2: [] //导演下拉项列表
})

//影片分类change事件
const handleSelectChange = (value: any, selectedOptions: any) => {
  if (!value) {
    formState.video_categ_id = undefined
    formState.video_subcateg_id = undefined
    return false
  }
  formState.video_categ_id = value[0]
  formState.video_subcateg_id = value[1]
}
//演员change
const handleActorChange = (value: string[], option: any) => {
  console.log('value: ', value, option)
  option.forEach((item: any, index: number) => {
    if (!item.person_name && !item.person_id) {
      item.person_name = ''
      item.person_id = 0
    }
  })
  const arr = value.toString().split(',')
  option.forEach((item: any, index: number) => {
    item.person_name = arr[index]
  })
  formState.actor = [...option]
}
//导演change
const handleDirectorChange = (value: string[], option: any) => {
  option.forEach((item: any, index: number) => {
    if (!item.person_name && !item.person_id) {
      item.person_name = ''
      item.person_id = 0
    }
  })
  const arr = value.toString().split(',')
  option.forEach((item: any, index: number) => {
    item.person_name = arr[index]
  })
  formState.director = [...option]
  console.log(formState.director, 'formState.director')
}
const handlePriceChange = () => {
  formState.video_price = undefined
  basicRef.value.clearValidate('video_price')
}
//添加一组播放地址
const addAddress = () => {
  const list = formState.video_play_url
  console.log('video_play_url-list: ', list)
  const len = list.length + 1
  console.log('video_play_url-len: ', len)
  list.push({
    number: len,
    name: '',
    urls: []
  })
}
/** {
        order: 1,
        name: '第1集',
        url: '',
        seed_mark: ''
      } */
//新增一集
const addNewEpisode = (index: number) => {
  const list = formState.video_play_url[index].urls
  const len = list.length + 1
  formState.video_play_url[index].urls.push({
    order: len,
    name: `第${len}集`,
    url: undefined,
    seed_mark: undefined
  })
}
//删除一集
const deleteItem = (list: any, index: number) => {
  list.splice(index, 1)
}
//清空
const clearAddress = (index: number) => {
  formState.video_play_url[index].urls = []
  /**
  {
      name: `第1集`,
      url: undefined,
      order: 1,
      seed_mark: undefined
    }
   */
}
//反序
const reverseAddress = (item: any, index: number) => {
  item.urls.reverse().forEach((item: any, index: number) => (item.name = `第${index + 1}集`))
}
//校正
const adjustAddress = (item: any) => {
  console.log('item: ', item)
  item.urls.forEach((subItem: any, index: any) => {
    subItem.name = `第${index + 1}集`
  })
}
//删除
const deleteAddress = (index: number) => {
  const len = formState.video_play_url.length
  if (len === 1) return message.warning('不能删除了喔!')
  formState.video_play_url.splice(index, 1)
}
//重置表单
const resetFormFunc = () => {
  basicRef.value?.resetFields()
  formState.video_release_date = undefined
  formState.video_cover_horizontal = undefined
  formState.video_cover_horizontal_type = 1
  formState.video_cover_vertical = undefined
  formState.video_cover_vertical_type = 1
  formState.video_album_ids = undefined
  formState.video_area_id = undefined
  formState.video_play_url = [
    {
      number: 1,
      name: '',
      urls: []
    }
  ]
  /**{
          order: 1,
          name: '第1集',
          url: '',
          seed_mark: ''
        } */
  formState.type_ids = []
  //重置扩展信息
  formState.video_name_alias = undefined
  formState.video_name_eng = undefined
  formState.video_keyword = undefined
  formState.video_tags = undefined
  formState.video_pop_add_star = 0
  formState.video_tags_copy = undefined
  isPopularity.value = false
  formState.actor = undefined
  formState.actor_copy = undefined
  formState.director = undefined
  formState.director_copy = undefined
  resetExtendFunc()
}

const validateFunc = () => {
  console.log('formState: ', formState)
  const params = { ...formState }
  basicRef.value
    .validate()
    .then(() => {
      if (!videoId.value) {
        params.site_id = siteId
        params.video_origin = siteType
        add_film(params).then(() => {
          message.success('保存影片成功')
          resetFormFunc()
          router.back()
        })
      } else {
        params.video_id = videoId.value
        update_film(params).then(() => {
          message.success('编辑影片成功')
          resetFormFunc()
          router.back()
        })
      }
    })
    .catch(() => {
      console.log(formState, 'formState12322')
      message.warning('请检查必填项是否完整')
    })
}
const commonFunc = (res: any) => {
  if (res.video_categ_id && res.video_categ_id != '0') classList.value?.push(res.video_categ_id)
  console.log('res.video_categ_id: ', res.video_categ_id)
  if (res.video_subcateg_id && res.video_subcateg_id != '0') classList.value?.push(res.video_subcateg_id)
  if (formState.publish_state === 0) formState.publish_state = undefined
  //扩展信息是否开启补偿
  if (formState.video_pop_compensated === 1) {
    isPopularity.value = true
  } else {
    isPopularity.value = false
  }
  //语言
  if (formState?.video_lang?.length === 0) formState.video_lang = undefined
  if (res.video_lang) {
    if (!langList.value.includes(res.video_lang)) {
      langList.value.push(res.video_lang)
    }
  }
  //年份
  if (formState?.video_year?.length === 0) {
    formState.video_year = undefined
  }
  //地区
  if (formState.video_area_id === '0') formState.video_area_id = undefined
  if (formState.video_episode_total === 0) formState.video_episode_total = undefined
  if (formState.video_episode === 0) formState.video_episode = undefined
  if (formState.video_duration === 0) formState.video_duration = undefined
  if (formState.video_score_imdb === 0) formState.video_score_imdb = undefined
  if (formState.video_score_douban === 0) formState.video_score_douban = undefined
  if (formState.video_cover_vertical) {
    if (formState.video_cover_vertical_type === 1) {
      verticalPreviewImage.value = baseUrl + formState.video_cover_vertical
    } else if (formState.video_cover_vertical_type === 2) {
      verticalPreviewImage.value = formState.video_cover_vertical
    } else {
      formState.video_cover_vertical_type = 1
    }
  } else {
    formState.video_cover_vertical_type = 1
    formState.video_cover_vertical = undefined
  }
  if (formState.video_cover_horizontal) {
    if (formState.video_cover_horizontal_type === 1) {
      horizontalPreviewImage.value = baseUrl + formState.video_cover_horizontal
    } else if (formState.video_cover_horizontal_type === 2) {
      horizontalPreviewImage.value = formState.video_cover_horizontal
    } else {
      formState.video_cover_horizontal_type = 1
    }
  } else {
    formState.video_cover_horizontal_type = 1
    formState.video_cover_horizontal = undefined
  }
  //如果播放资源为空数组，设置默认一条数据
  if (formState.video_play_url.length <= 0) addAddress()
  //截取前50个字符
  if (formState?.video_name ?? ''.length > 50) formState.video_name = formState?.video_name?.substring(0, 49)
  if (formState?.video_name_alias ?? ''.length > 100)
    formState.video_name_alias = formState?.video_name_alias?.substring(0, 99)
  if (formState?.video_introduction ?? ''.length > 1000)
    formState.video_introduction = formState?.video_introduction?.substring(0, 1000)
  if (formState?.video_highlight ?? ''.length > 1000)
    formState.video_highlight = formState?.video_highlight?.substring(0, 1000)
  if (formState?.video_note ?? ''.length > 1000) formState.video_note = formState?.video_note?.substring(0, 1000)
  if (!formState.video_price_type) formState.video_price_type = 1
  if (!formState.video_status) formState.video_status = 1

  console.log('res.actor.length: ', res.actor.length)
  if (res.actor.length) {
    formState.actor_copy = res.actor.map((item: any) => {
      return item.person_name
    })
    console.log('formState.actor_copy: ', formState.actor_copy)
  }
  if (res.director.length) {
    formState.director_copy = res.director.map((item: any) => {
      return item.person_name
    })
  }
  if (res.video_tags.length) {
    formState.video_tags_copy = res.video_tags.map((item: any) => {
      return item.tag_name
    })
  }
  if (res.video_types.length) {
    formState.type_ids = res.video_types.map((item: any) => {
      return item.type_id
    })
  }
  formState.video_pop_add_star = getMax(formState.video_pop_add_star, formState.video_pop_star)
  formState.video_pop_add_score = getMax(formState.video_pop_add_score, formState.video_pop_score)
  if (res.video_album.length > 0) {
    formState.video_album_ids = res.video_album.map((item: any) => {
      return item.album_id
    })
  }
  console.log('formState: ', formState)
}
const getMax = (val: number, val1: number) => {
  return Math.max(val, val1)
}
//根据影片名称查列表
const handleListByName = () => {
  if (!formState.video_name) return message.warning('影片名称不能为空')
  nameLoading.value = true
  detail_film_byFilmName({ video_name: formState.video_name })
    .then((res: any) => {
      console.log(res, '影片列表res')
      nameLoading.value = false
      videoList.value = res?.videos ?? []
      console.log('videoList: ', videoList)
      if (videoList.value.length === 1) {
        formState.beanId = videoList.value[0].douban_id
        handleDetailByBeanId()
      } else if (videoList.value.length > 1) {
        filmVisible.value = true
      } else {
        message.warning('未查询到影片')
      }
    })
    .catch(() => {
      nameLoading.value = false
    })
}
//根据豆瓣id查询详情
const handleDetailByBeanId = () => {
  if (!formState.beanId) return message.warning('豆瓣ID不能为空')
  beanLoading.value = true
  detail_film_byBeanId({ douban_id: formState.beanId, site_id: siteId })
    .then((res: any) => {
      beanLoading.value = false
      console.log('res: ', res)
      verticalPreviewImage.value = ''
      horizontalPreviewImage.value = ''
      if (res.video_area_id == '0') delete res.video_area_name
      // let key: keyof any
      // for (key in res) {
      //   if (!res[key]) {
      //     delete res[key]
      //   } else if (res[key].length <= 0) {
      //     delete res[key]
      //   } else if (res[key] === '0') {
      //     delete res[key]
      //   }
      // }

      if (!res.video_categ_id || res.video_categ_id === '0') delete res.video_categ_id
      if (!res.video_subcateg_id || res.video_subcateg_id === '0') delete res.video_subcateg_id
      if (!res.video_album.length) delete res.video_album
      if (!res.actor.length) delete res.actor
      if (!res.video_area_id || res.video_area_id === '0') delete res.video_area_id
      if (!res.video_year || res.video_year === '0') delete res.video_year
      if (!res.video_lang || res.video_lang === '0') delete res.video_lang
      if (!res.video_episode || res.video_episode === '0') delete res.video_episode
      if (!res.video_episode_total || res.video_episode_total === '0') delete res.video_episode_total
      if (!res.video_release_date || res.video_release_date === '0') delete res.video_release_date
      if (!res.video_duration || res.video_duration === '0') delete res.video_duration
      if (!res.video_score_douban || res.video_score_douban === 0) delete res.video_score_douban
      if (!res.video_score_imdb || res.video_score_imdb === 0) delete res.video_score_imdb
      if (!res.video_note || res.video_note === '0') delete res.video_note
      if (!res.video_highlight || res.video_highlight === '0') delete res.video_highlight

      const {
        video_play_url,
        video_pop_add_collection,
        video_pop_add_day,
        video_pop_add_like,
        video_pop_add_month,
        video_pop_add_people_count,
        video_pop_add_score,
        video_pop_add_share_count,
        video_pop_add_star,
        video_pop_add_total,
        video_pop_add_view,
        video_pop_add_week,
        video_pop_day,
        video_pop_like,
        video_pop_month,
        video_pop_people_count,
        video_pop_score,
        video_pop_share_count,
        video_pop_star,
        video_pop_total,
        video_pop_view,
        video_pop_week,
        ...data
      } = res
      Object.assign(formState, data)
      console.log('formState222222222222: ', formState)
      commonFunc(data)
    })
    .catch(() => {
      beanLoading.value = false
    })
}
//获取图集详情
const getVideoDetail = () => {
  detail_film({ video_id: videoId.value }).then((res: any) => {
    console.log('res: ', res)
    // res.chapters.forEach((item: chaptersItem) => {
    //   item.is_edit = false
    // })
    Object.assign(formState, res)
    commonFunc(res)
  })
}
const init = () => {
  getArea()
  getVideoList()
  getAlbumList()
  // getPersonList()
  getVideoOption()
}
//根据分类查类型
watch(
  () => formState.video_categ_id,
  (val, oldVal) => {
    if (val != oldVal && val != '0') getTypeByClass()
  },
  {
    deep: true
  }
)
watch(
  () => formState.video_name,
  (val, oldVal) => {
    if (val !== oldVal && formState.beanId) {
      console.log('video_name改变了===========: ', val)
      resetExtendFunc()
    }
  },
  { deep: true }
)
watch(
  () => route.name,
  () => {
    resetFormFunc()
  },
  { deep: true }
)
defineExpose({ validateFunc })
const tableRefs: any = ref([])
const setItemRef = (el: any) => {
  if (el) tableRefs.value.push(el)
}
console.log('tableRefs11: ', tableRefs.value)
//初始化表格拖动
const initSortable = () => {
  console.log(tableRefs.value, tableRefs.value.length, 'tableRefs')
  tableRefs.value.forEach((item: any) => {
    console.log('item123123: ', item)
    const el = item.table.$el.querySelector('#basicSortTable tbody') as HTMLElement
    // const el = document.querySelector('#basicSortTable tbody') as HTMLElement
    console.log({ el })
    new Sortable(el, {
      handle: '.ant-table-row',
      animation: 150,
      ghostClass: 'blue-background-class',
      forceFallback: true,
      sort: true,
      // async
      onEnd(item) {
        console.log({ item })
        if (item.newIndex === item.oldIndex) return
        //   const startIndex = (item.oldIndex as number) - 1
        //   const endIndex = (item.newIndex as number) - 1
        //   const { id } = state.startAdList[startIndex]
        //   const { order } = state.startAdList[endIndex]
      }
    })
  })
}
// nextTick(() => initSortable())
onMounted(() => {
  init()
  videoId.value = router.currentRoute.value.query?.id as string
  console.log('videoId.value: ', videoId.value)
  if (!videoId.value) return false
  getVideoDetail()
})
onUnmounted(() => {
  tableRefs.value = []
  resetFormFunc()
})
</script>

<style lang="less" scoped>
.page-basic {
  :deep(.ant-form) {
    .m-r-120 {
      margin-right: 120px;
    }

    .m-r-106 {
      margin-right: 106px;
    }

    .page-basic-hasBtn {
      display: flex;
      flex-wrap: nowrap;
      width: 100%;

      .ant-form-item-control-input-content {
        display: flex;
        width: 33%;

        .input-w-304 {
          width: 304px;
        }
      }
    }

    .page-basic-classify {
      display: flex;
      width: 100%;

      .ant-form-item-control-input-content {
        .select-w-200 {
          width: 200px;
        }
      }
    }

    .page-basic-three-column {
      width: 100%;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      flex-wrap: wrap;
    }

    /**
      .page-basic-three-column::after {
      content: '';
      flex: 1;
    }
    */

    .page-basic-filmType {
      width: 90%;
      display: flex;
      flex-wrap: wrap;

      .ant-checkbox-wrapper {
        margin: 4px 0;
      }
    }

    .page-basic-common {
      width: 90%;
      padding: 24px 0 0;
      box-sizing: border-box;
      border-bottom: 1px solid #f0f0f0;

      &-title {
        font-size: 16px;
        color: #262626;
        letter-spacing: 1.14px;
        font-weight: 500;
        margin-bottom: 24px;
      }

      &-cover {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }

      .ant-table .ant-table-container::after {
        width: 0px;
      }

      .address-content {
        margin-left: 72px;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        &-playAddress {
          width: 48%;
          margin: 8px 0;

          &-top {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            align-items: baseline;

            .left-title {
              margin-bottom: 4px;

              &-title {
                font-size: 14px;
                color: #262626;
                letter-spacing: 0;
                margin-right: 5px;
              }
            }

            .right-btn {
              margin-left: 5px;

              .ant-btn {
                height: 26px;
                line-height: 26px;
                margin-bottom: 5px;
              }

              .ant-btn:not(:last-child) {
                margin-right: 8px;
              }

              .ant-btn:last-child {
                background: rgba(254, 76, 77, 0.08);
                border: 1px solid rgba(254, 76, 77, 1);
              }
            }
          }

          &-addressText {
            width: 100%;
            margin: 8px 0 9px;
            border: 1px solid rgba(217, 217, 217, 1);
            border-radius: 3px;
            .ant-table-body {
              min-height: 171px;
            }

            .ant-table-tbody > tr > td,
            .ant-table tfoot > tr > th,
            .ant-table tfoot > tr > td {
              position: relative;
              padding: 8px 16px;
              overflow-wrap: break-word;
            }

            .episodeStyle {
              width: 94px;
              height: 32px;
              line-height: 32px;
              text-align: center;
              background: #ffffff;
              border: 1px solid rgba(0, 0, 0, 0.15);
              border-radius: 3px;
            }

            .ant-form-item-control-input-content {
              .input-h-160 {
                width: 100%;
                height: 160px;
              }
            }
          }
        }
      }

      .m-t-34 {
        margin-top: 34px;
      }

      .w-480 {
        width: 480px;
      }

      .source-introduce {
        margin-top: 8px;
        font-size: 12px;
        color: #bfbfbf;
      }

      .ant-form-item-control-input-content {
        display: flex;

        .ant-radio-group {
          margin: 5px 0 15px !important;
        }
      }
    }
  }
}
</style>
